package top.huxy.mybatis.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Component;
import top.huxy.mybatis.core.DataSource;
import top.huxy.mybatis.core.DynamicDataSource;

import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class DataSourceAspect implements Ordered {

    @Value("${spring.defaultDataSource:}")
    String defaultDataSource;

    @Pointcut("@annotation(top.huxy.mybatis.core.DataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Method method = ((MethodSignature) point.getSignature()).getMethod();

        DataSource ds = method.getAnnotation(DataSource.class);
        String dataSource = null;
        if (ds == null || defaultDataSource == null || defaultDataSource.trim().length() == 0) {
            dataSource = HuxyDataSourceAutoConfig.DEFAULT_DATA_SOURCE_NAME;
        } else {
            dataSource=ds.name();
        }
        DynamicDataSource.setDataSource(dataSource);

        try {
            return point.proceed();
        } catch (BadSqlGrammarException e) {
            log.warn("SQL异常，请检查数据源、SQL语句是否正确，本次数据源:{}", dataSource);
            throw e;
        } finally {
            DynamicDataSource.clearDataSource();
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}